/*build.cpp
 *This program builds RAID.
 *Created on: 2013.12.24
 *Author: Petrunin D.S.
 */

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <cstring>

using namespace std;

int buildDisks(int nDisks, int nBlocks, int blockS, int RAIDN) {

	FILE* config = fopen("conf", "w");
  if (config == NULL) {
  	cout<<"Can't open config file.\n";
    return 1;
  }
  fprintf(config, "%i\n", nDisks);
	fprintf(config, "%i\n", nBlocks);
	fprintf(config, "%i\n", blockS);
	fprintf(config, "%i\n", RAIDN);
	fclose(config);
	char DiskNm[10];
	FILE* disk;
	char* diskData = new char[blockS*nBlocks];
	//Create disks
	for(int i = 1; i <= nDisks; i++) {
	  sprintf(DiskNm, "Disk%i", i);
	  disk = fopen(DiskNm, "wb+");
	  if (disk == NULL) {
	    cout<<"Can't open file Disk" << i <<"\n";
	    return 1;
	  }
		fwrite(diskData, sizeof(char), blockS*nBlocks, disk);
		fclose(disk);
	}
	delete[] diskData;
	cout<<"Successfull build of RAID "<<RAIDN<<".\n";
	return 0;
}


int main(int argc, char* argv[]) {

	if (argc < 5) {
		cout << "Not enough parameters\n";
		return 1;
	}
	int nDisks = atoi(argv[1]);
	if ((nDisks < 4)||(nDisks > 8)||(nDisks % 2 != 0)) {
		cout << "Number of disks must be even and lie in the range from 4 to 8.\n";
		return 1;
	}
	int nBlocks = atoi(argv[2]);
	if ((nBlocks < 100)||(nBlocks > 10000)) {
		cout << "Number of blocks must be in range 100..10000.\n";
		return 1;
	}
	int blockS = atoi(argv[3]);
	if ((blockS < 256)||(blockS > 2048)) {
		cout << "Size of block must be in range 256..2048.\n";
		return 1;
	}
	int RAIDN;
	char level[2];
	level[0] = argv[4][0];
	level[1] = argv[4][1];
	if ((level[0] == '0') && (level[1] == '1'))
		RAIDN = 0;
	else {
		if ((level[0] == '1') && (level[1] == '0'))
			RAIDN = 1;
		else {
			cout <<"Level of RAID must be either 01 or 10.\n";
			return 1;
		}
	}

	return buildDisks(nDisks, nBlocks, blockS, RAIDN);
}
